#include "bsp_adc.h"
#include "public_macro.h"



#define TEST_CONV_LENGTH      (128UL)

volatile uint16_t covn_done = 0;
uint16_t conversion[TEST_CONV_LENGTH];
double   voltage[TEST_CONV_LENGTH];
app_adc_params_t adc_params = {
    .pin_cfg = {
        .channel_p = {
            .type = APP_IO_TYPE_MSIO,
            .mux  = APP_ADC_P_INPUT_PIN_MUX,
            .pin  = APP_ADC_P_INPUT_PIN,
        },
        .channel_n = {
            .type = APP_IO_TYPE_MSIO,
            .mux  = APP_ADC_N_INPUT_PIN_MUX,
            .pin  = APP_ADC_N_INPUT_PIN,
        },
    },
    .dma_cfg = {
        .dma_instance = DMA0,
        .dma_channel  = DMA_Channel0,
    },
    .init = {
        .channel_p  = ADC_INPUT_SRC_IO1,
        .channel_n  = ADC_INPUT_SRC_IO1,
        .input_mode = ADC_INPUT_SINGLE,
        .ref_source = ADC_REF_SRC_BUF_INT,
        .ref_value  = ADC_REF_VALUE_1P6,
        .clock      = ADC_CLK_1P6M,
    },
};

void app_adc_evt_handler(app_adc_evt_t * p_evt)
{
    if (p_evt->type == APP_ADC_EVT_CONV_CPLT)
    {
        covn_done = 1;
        GR_LOG("DMA conversion is done.\r\n");
    }
}

void user_adc_init(void)
{
    app_adc_deinit();
    app_adc_dma_deinit();
}


void adc_single(void)
{
    app_adc_deinit();
    app_adc_init(&adc_params, app_adc_evt_handler);
    app_adc_dma_deinit();
    app_adc_dma_init(&adc_params);

    memset(conversion, 0, sizeof(conversion));

    GR_LOG("Start single sampling.\r\n");
    covn_done = 0;
    app_adc_dma_conversion_async(conversion, TEST_CONV_LENGTH);
    while(covn_done == 0);

    app_adc_voltage_intern(conversion, voltage, TEST_CONV_LENGTH);
    printf("Conversion value:\r\n");
    for(uint32_t i = 0; i < TEST_CONV_LENGTH; i++)
    {
        GR_LOG(" [%d] %0.3fV \r\n", i, voltage[i]);
        app_log_flush();
    }
    GR_LOG("\r\n");
}


int readMagneticData(void)
{
    app_adc_deinit();
    app_adc_init(&adc_params, app_adc_evt_handler);
    app_adc_dma_deinit();
    app_adc_dma_init(&adc_params);

    memset(conversion, 0, sizeof(conversion));
    covn_done = 0;
    app_adc_dma_conversion_async(conversion, TEST_CONV_LENGTH);
    while(covn_done == 0);
    app_adc_voltage_intern(conversion, voltage, TEST_CONV_LENGTH);
//    printf("Conversion value:\r\n");
//    for(uint32_t i = 0; i < TEST_CONV_LENGTH; i++)
//    {
//        GR_LOG("%0.3fV, ", i, voltage[i]);
//    }
//    GR_LOG("\r\n");
    app_adc_deinit();
    app_adc_dma_deinit();
    return (int)(voltage[0]*1000);
}

int adc_loop(void)
{

    for(;;)
    {
        adc_single();
        delay_ms(500);
    }
//    adc_single();

//    printf("\r\nThis example demo end.\r\n");

//    while(1);
}

